package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseTimeDialogFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.RequisitionDetail;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.DateUtil;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.Date;
import java.util.HashMap;
import org.json.JSONException;

public class CheckOverFragment extends CheckDetailFragment {
  //protected static final int REQUEST_PLAN_DATE_START = 0;
  //protected static final int REQUEST_PLAN_DATE_END = 3;
  protected static final int REQUEST_ACTUAL_DATE_END = 1;
  protected static final int REQUEST_ACTUAL_DATE_START = 2;

  private EditText mEtReason;
  private TextView mTvActualStartTime;
  private TextView mTvActualEndTime;
  private EditText mEtActualHours;

  /**
   * Find the Views in the layout<br />
   * <br />
   * Auto-created on 2015-12-10 12:17:30 by Android Layout Finder
   * (http://www.buzzingandroid.com/tools/android-layout-finder)
   */
  private void findViews(View v) {

    mEtReason = (EditText) v.findViewById(R.id.et_overTimeReason_checkOver);
    mTvActualStartTime = (TextView) v.findViewById(R.id.tv_actualBeginTime_checkOver);
    mTvActualEndTime = (TextView) v.findViewById(R.id.tv_actualEndTime_checkOver);
    mEtActualHours = (EditText) v.findViewById(R.id.et_actualOverTimeHours_checkOver);
    /**
     * 计划开始时间
     */

    mTvActualStartTime.setOnClickListener(new OnClickListener() {
      @Override public void onClick(View v) {

        showDialog(mTvActualStartTime.getText().toString().trim(), R.string.chooseTime,
            REQUEST_ACTUAL_DATE_START);
      }
    });
    mTvActualEndTime.setOnClickListener(new OnClickListener() {
      @Override public void onClick(View v) {

        showDialog(mTvActualEndTime.getText().toString().trim(), R.string.chooseTime,
            REQUEST_ACTUAL_DATE_END);
      }
    });

    if (mMenuType == CHECK_PASS || mMenuType == WAIT_CHECK) {
      mEtReason.setEnabled(false);
      mTvActualStartTime.setEnabled(false);
      mTvActualEndTime.setEnabled(false);
      mEtActualHours.setEnabled(false);
    }
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    setTitleCustom(R.string.requisitionover);
    View view = inflater.inflate(R.layout.fragment_check_over, container, false);
    findViews(view);
    initDetailData();

    return view;
  }

  private void initDetailData() {
    mEtActualHours.setText("0.0");
    if (mMenuType != ADD) {
      volleypostInit();
    }
  }

  private void volleypostInit() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_REQUISITION_DETAIL);
    HashMap<String, String> params = new HashMap<>();
    params.put("attendType", mType);
    params.put("id", mId);

    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String response) {

        MyUtils.dismissDialog();
        try {
          RequisitionDetail requisitionDetail =
              new Gson().fromJson(response, RequisitionDetail.class);

          mEtReason.setText(requisitionDetail.getOvertimeReason());
          mTvActualStartTime.setText(requisitionDetail.getActSTime());
          mTvActualEndTime.setText(requisitionDetail.getActETime());
          mEtActualHours.setText(requisitionDetail.getActWorkNum());
        } catch (JsonSyntaxException e) {
          LogUtil.e("error", e);
          ToastUtil.show(R.string.wrong_data);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        MyUtils.dismissDialog();
        ToastUtil.show(R.string.noConnectionToServer);
      }
    });
  }

  private void showDialog(String startDate, int titleId, int requestCode) {

    Date date = DateUtil.stringToDate(startDate);
    if (null == date) {
      date = new Date();
    }
    FragmentManager fm = getActivity().getSupportFragmentManager();
    DialogFragment dialog = BaseTimeDialogFragment.newInstance(date, titleId);
    dialog.setTargetFragment(CheckOverFragment.this, requestCode);
    dialog.show(fm, "");
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode != Activity.RESULT_OK) return;
    String startDate;// 开始时间
    String endDate;// 结束时间

    if (requestCode == REQUEST_ACTUAL_DATE_START) {
      Date resultData = (Date) data.getSerializableExtra(BaseTimeDialogFragment.EXTRA_DATE);

      String dateString = DateUtil.dateToString(resultData);

      mTvActualStartTime.setText(dateString);
      startDate = mTvActualStartTime.getText().toString().trim();
      endDate = mTvActualEndTime.getText().toString().trim();
      // 获取工时
      getWorkHours(requestCode, startDate, endDate);
    }
    if (requestCode == REQUEST_ACTUAL_DATE_END) {
      Date resultData = (Date) data.getSerializableExtra(BaseTimeDialogFragment.EXTRA_DATE);

      String dateString = DateUtil.dateToString(resultData);

      mTvActualEndTime.setText(dateString);
      startDate = mTvActualStartTime.getText().toString().trim();
      endDate = mTvActualEndTime.getText().toString().trim();
      // 获取工时
      getWorkHours(requestCode, startDate, endDate);
    }
    if (requestCode == REQUEST_DELETE) {
      volleyPostDelete();
    }
    if (requestCode == REQUEST_SUBMIT) {
      volleyPostSave(TYPE_RUN);
    }

    super.onActivityResult(requestCode, resultCode, data);
  }

  private void getWorkHours(final int requestCode, String startTime, String endTime) {

    if (TextUtils.isEmpty(startTime) || TextUtils.isEmpty(endTime)) {
      return;
    }
    if (DateUtil.before(endTime, startTime)) {
      return;
    }
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_REQUISITION_OVER_WORKHOUR);
    HashMap<String, String> params = new HashMap<>();
    params.put("sTime", startTime);
    params.put("eTime", endTime);
    MyUtils.showDialogLoading(getActivity(), R.string.loadingWorkHour);
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) {
        MyUtils.dismissDialog();
        try {
          SuccessMessage successMessage = new Gson().fromJson(arg0, SuccessMessage.class);
          if (successMessage.getResult().equals(SuccessMessage.SUCCESS)) {
            String message = successMessage.getMessage();

            if (requestCode == REQUEST_ACTUAL_DATE_START
                || requestCode == REQUEST_ACTUAL_DATE_END) {
              mEtActualHours.setText(message);
            }
          }
        } catch (Exception e) {
          LogUtil.e("workTimeOverError=" + e, e);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        MyUtils.dismissDialog();
      }
    });
  }

  @Override public boolean isCorrectInput() {
    // 验证文本信息
    String reasonString = mEtReason.getText().toString().trim();
    //String currentTime = DateUtil.dateToString(new Date());// 当前时间
    //		String planBeginTime = mTvPlanStartTime.getText().toString().trim();
    //		String planEndTime = mTvPlanEndTime.getText().toString().trim();
    //		String actualBeginTime = mTvActualStartTime.getText().toString().trim();
    //		String actualEndTime = mTvActualEndTime.getText().toString().trim();
    String actualBeginTime = mTvActualStartTime.getText().toString().trim();
    String actualEndTime = mTvActualEndTime.getText().toString().trim();
    //		String planHours = mEtPlanHours.getText().toString().trim();
    String planHours = mEtActualHours.getText().toString().trim();
    if (TextUtils.isEmpty(reasonString)) {
      Toast.makeText(getActivity(), R.string.no_content, Toast.LENGTH_SHORT).show();
      return false;
    }
    if (TextUtils.isEmpty(actualBeginTime)) {
      Toast.makeText(getActivity(), R.string.chooseRealStartTime, Toast.LENGTH_SHORT).show();
      return false;
    }
    if (TextUtils.isEmpty(actualEndTime)) {
      Toast.makeText(getActivity(), R.string.chooseRealEndTime, Toast.LENGTH_SHORT).show();
      return false;
    }
    if (TextUtils.isEmpty(planHours)) {
      Toast.makeText(getActivity(), R.string.no_outover_hours, Toast.LENGTH_SHORT).show();
      return false;
    }
    //		if ("0.0".equalsIgnoreCase(planHours) || "0".equalsIgnoreCase(planHours)) {
    //			Toast.makeText(getActivity(), R.string.planTimeNotZero, Toast.LENGTH_SHORT).show();
    //			return false;
    //		}
    //		if (DateUtil.before(planEndTime, planBeginTime)) {
    //			Toast.makeText(getActivity(), R.string.planEndTimeAfterStartTime, Toast.LENGTH_SHORT).show();
    //			return false;
    //		}

    //		if (!TextUtils.isEmpty(actualBeginTime) && TextUtils.isEmpty(actualEndTime)) {
    //			ToastUtil.show(R.string.chooseRealEndTime);
    //
    //			return false;
    //		}
    //		if (!TextUtils.isEmpty(actualEndTime) && TextUtils.isEmpty(actualBeginTime)) {
    //			ToastUtil.show(R.string.chooseRealStartTime);
    //			return false;
    //		}
    //		if (!TextUtils.isEmpty(actualEndTime) && DateUtil.before(currentTime, actualEndTime)) {
    //			ToastUtil.show(R.string.realEndTimeBdforeCurrent);
    //			return false;
    //		}
    //		if (!TextUtils.isEmpty(actualBeginTime) && DateUtil.before(currentTime, actualBeginTime)) {
    //			ToastUtil.show(R.string.realStartTimeBeforeCurrent);
    //			return false;
    //		}

    if (!DateUtil.before(actualBeginTime, actualEndTime)) {
      ToastUtil.show(R.string.realEndTimeAfterRealStartTime);
      return false;
    }

    return true;
  }

  @Override protected void volleyPostSave(final String type) {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_REQUISITION_SAVE_OR_RUN);

    HashMap<String, String> params = new HashMap<>();
    params.put("attendType", CheckDetailFragment.VALUE_OVER);
    params.put("saveOrRun", type);
    params.put("overtimeReason", mEtReason.getText().toString().trim());
    params.put("planSTime", mTvActualStartTime.getText().toString().trim());
    params.put("planETime", mTvActualEndTime.getText().toString().trim());

    //		String planWorkHour = mEtActualHours.getText().toString().trim();
    //		if (TextUtils.isEmpty(planWorkHour)) {
    //			planWorkHour = "0.0";
    //		}
    //		params.put("panWorkNum", planWorkHour);// 计划工时
    //		if (mCbExtra.isChecked()) {
    //			cbStatus = "1";
    //		} else {
    //			cbStatus = "0";
    //		}
    params.put("overtimeType", "1");/*是否是补填*/
    params.put("actSTime", mTvActualStartTime.getText().toString().trim());
    params.put("actETime", mTvActualEndTime.getText().toString().trim());

    String actualWorkHour = mEtActualHours.getText().toString().trim();
    if (TextUtils.isEmpty(actualWorkHour)) {
      actualWorkHour = "0.0";
    }
    params.put("actWorkNum", actualWorkHour);// 实际工时
    params.put("panWorkNum", actualWorkHour);// 计划工时
    if (mMenuType != ADD) {
      params.put("id", mId);
      if (TYPE_RUN.equals(type)) {

        params.put("isList", "0");
        params.put("dataStatus", "waitCheck");
      }
    }
    //		if ("abort".equalsIgnoreCase(mDataStatus)) {
    //			params.put("dataStatus", "new");
    //		}
    LogUtil.i("overParams=" + params.toString());
    if (TYPE_RUN.equals(type)) {

      MyUtils.showDialogLoading(getActivity(), R.string.loadingStart);
    }
    if (TYPE_SAVE.equals(type)) {

      MyUtils.showDialogLoading(getActivity(), R.string.loadingSave);
    }

    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) {

        MyUtils.dismissDialog();
        try {

          SuccessMessage successsMessage = new Gson().fromJson(arg0, SuccessMessage.class);

          String successType = successsMessage.getResult();

          switch (successType) {
            case "1":
              getActivity().setResult(Activity.RESULT_OK);
              ToastUtil.show(R.string.success_operation);
              getActivity().finish();
              break;
            case "0":
              //						Toast.makeText(getActivity(), successsMessage.getMessage(), Toast.LENGTH_SHORT).show();
              showErrorDialog(successsMessage.getMessage());
              break;
            default:
              ToastUtil.show(R.string.failure_operation);
              break;
          }
        } catch (Exception e) {
          LogUtil.e("error", e);
          ToastUtil.show(R.string.failure_operation);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {

      }
    });
  }

  private void volleyPostDelete() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_REQUISITION_DELETE);
    HashMap<String, String> params = new HashMap<>();
    params.put("ids", mType + "#" + mId);
    MyUtils.showDialogLoading(getActivity(), R.string.loadingDelete);
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        MyUtils.dismissDialog();
        try {

          SuccessMessage successsMessage = new Gson().fromJson(arg0, SuccessMessage.class);

          String successType = successsMessage.getResult();

          if (successType.equals("1")) {
            getActivity().setResult(Activity.RESULT_OK);
            ToastUtil.show(R.string.success_operation);
            getActivity().finish();
          } else {
            ToastUtil.show(R.string.failure_operation);
          }
        } catch (Exception e) {
          LogUtil.e("error", e);
          ToastUtil.show(R.string.failure_operation);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        // Auto-generated method stub

      }
    });
  }
}
